<?php
namespace App\Service\ApiQd;

use Illuminate\Support\Facades\DB;

class OrderService extends BaseService
{
    //订单

    /**
     * 列表
     * @param int $uid 用户ID
     * @param int $status 0所有，1待付款，2待发货，3待收货，4完成
     * @param array $pages【start，limit】
     */
    public function getList($uid, $pages, $status = 0)
    {
        $this->autoAccept($uid); //自动收货
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbwbConn($this->dbDistributorOrder);
        $ws[] = ['del', '=', 0];
        $ws[] = ['uid', '=', $uid];
        if ($status > 0) {
            if ($status == 1) {//待付款
                $ws[] = ['iscancel', '=', 1];
                $ws[] = ['status', '=', 1];
                $db = $db->where($ws);
            } else if ($status == 2) {//待发货
                $ws[] = ['iscancel', '=', 1];
                $ws[] = ['status', '=', 2];
                $db = $db->where($ws);
            } else if ($status == 3) {//待收货
                $ws[] = ['iscancel', '=', 1];
                $ws[] = ['status', '=', 3];
                $db = $db->where($ws);
            } else if ($status == 4) {//完成+售后
//                $ws[] = ['iscancel', '=', 1];
//                $ws[] = ['status', '=', 4];
//                $db = $db->where($ws);
                $w01 = $ws; $w02 = $ws;
                $w01[] = ['iscancel', '=', 1];
                $w01[] = ['status', '=', 4];
                $w02[] = ['iscancel', '=', 3];
                $db = $db->where($w01)->orWhere($w02);
            } else if($status == 5){//已取消
                $ws[] = ['iscancel', '=', 2];
                $db = $db->where($ws);
            }
        } else {
            $db = $db->where($ws);
        }
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有订单', 'data'=> [], 'total' => 0);
        }
        $status1s = $this->orderStatus1s;
        $cancels = $this->orderCancels;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            //下单时间
            $ordertime = strtotime($v['addtime']);
            //订单状态
            if ($v['iscancel'] > 1) {
                $status_name = array_key_exists($v['iscancel'], $cancels) ? $cancels[$v['iscancel']] : '';
            } else {
                $status_name = array_key_exists($v['status'], $status1s) ? $status1s[$v['status']] : '';
            }
            //商品图片
            $gArys = [];
            $sale = 0;
            $osOnes = $this->dbwbConn($this->dbDistributorOsku)->where('order_id', $v['id'])->get();
            if (count($osOnes)) {
                $gids = [];
                foreach ($osOnes as $osOne) {
                    $osOne = (array) $osOne;
                    $imgOne = (array) $this->dbwbConn($this->dbDistributorGimg)
                        ->where('del', 0)
                        ->where('gid', $osOne['gid'])
                        ->first();
                    $gOne = (array) $this->dbwbConn($this->dbDistributorGoods)
                        ->where('del', 0)
                        ->where('id', $osOne['gid'])
                        ->first();
                    if (!in_array($osOne['gid'], $gids) && !empty($imgOne) && !empty($gOne)) {
                        $gArys[] = [
                            'gid' => $osOne['gid'],
                            'sku_id' => $osOne['sku_id'],
                            'gname' => $gOne['title'],
                            'gimg' => env('DOMAIN') . '/' . $imgOne['link'],
                            'sku_name' => $osOne['sku_name'],
                        ];
                        $gids[] = $osOne['gid'];
                    }
                    $sale += $osOne['num'];
                }
            }
            $arys[] = [
                'id' => $v['id'],
                'orderno' => $v['orderno'],
                'ordertime' => date('Y-m-d H:i', $ordertime),
                'status' => $v['status'],
                'status_name' => $status_name,
                'iscancel' => $v['iscancel'],
                //'cancel_name' => $cancel_name,
                'wuliu' => $v['wuliu'],
                'wuliuhao' => $v['wuliuhao'],
                'goodsList' => $gArys,
                'priceTotal' => toNumber($v['price']),
                'num' => $v['num'],
                'uid' => $uid,
                'tradeno' => $v['tradeno'],
                'sale' => $sale,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data'=> $arys, 'total' => $total);
    }

    //下单前选项
    public function getOption()
    {
        $arys = [];
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 购物车下单
     * @param array $pas
     */
    public function add($pas)
    {
        //用户信息
        $uOne = (array) $this->dbwbConn($this->dbDistributorUser)
            ->where('id', $pas['uid'])
            ->first();
        if (empty($uOne)) {
            return array('code' => -2, 'msg' => '用户不存在');
        }
        //收货地址
        $addressOne = (array) $this->dbwbConn($this->dbDistributorUaddress)
            ->where('del', 0)
            ->where('uid', $pas['uid'])
            ->where('id', $pas['address_id'])
            ->first();
        if (empty($addressOne)) {
            return array('code' => -2, 'msg' => '收货地址不存在');
        }
        //商品信息
        $cartids = explode(',', $pas['cart_ids']);
        $cartOnes = $this->dbwbConn($this->dbDistributorCart)
            ->where('del', 0)
            ->where('isorder', 0)
            ->where('uid', $pas['uid'])
            ->whereIn('id', $cartids)
            ->get();
        if (!count($cartOnes)) {
            return array('code' => -2, 'msg' => '购物车为空');
        }
        //订单信息
        $orderno = toOrderno();
        $priceTotal = $real_pay = $orderNum = 0;
        foreach ($cartOnes as $v) {
            $v = (array) $v;
            $priceTotal += $v['price'] * $v['num'];
            $orderNum += $v['num'];
        }
        $real_pay = $priceTotal;
        $orderData = [
            'from_type' => 1,
            'uid' => $pas['uid'],
            'uname' => $uOne['nickname'],
            'orderno' => $orderno,
            'tradeno' => toTradeno(),
            'address_id' => $pas['address_id'],
            'price' => $priceTotal,
            'real_pay' => $real_pay,
            'num' => $orderNum,
            'remark' => $pas['remark'],
            'addtime' => toDate(),
        ];
        DB::beginTransaction(); //开启事务
        try {
            //订单添加
            $orderid = $this->dbwbConn($this->dbDistributorOrder)->insertGetId($orderData);
            if (!$orderid) {
                return array('code'=>-1, 'msg'=>'下单失败');
            }
            //SKU信息
            foreach ($cartOnes as $v) {
                $v = (array) $v;
                $gArys = [
                    'order_id' => $orderid,
                    'gid' => $v['gid'],
                    'sku_id' => $v['sku_id'],
                    'gname' => $v['gname'],
                    'sku_name' => $v['sku_name'],
                    'gimg' => $v['gimg'],
                    'price' => $v['price'],
                    'num' => $v['num'],
                    'addtime' => toDate(),
                ];
                //订单SKU
                $osid = $this->dbwbConn($this->dbDistributorOsku)->insertGetId($gArys);
                if (!$osid) {
                    return array('code'=>-1, 'msg'=>'订单SKU失败');
                }
                //减库存更新
                $skuOne = (array) $this->dbwbConn($this->dbDistributorGsku)->where('id', $v['sku_id'])->first();
                if (empty($skuOne)) {
                    return array('code'=>-2, 'msg'=>'商品SKU失败');
                }
                if ($skuOne['stock'] < $v['num']) {
                    return array('code'=>-2, 'msg'=>'商品SKU不足');
                }
                $stockNew = $skuOne['stock'] - $v['num'];
                $skuData = [
                    'stock' => $stockNew,
                    'uptime' => toDate()
                ];
                $skuUp = $this->dbwbConn($this->dbDistributorGsku)->where('id', $v['sku_id'])->update($skuData);
                if (!$skuUp) {
                    return array('code'=>-2, 'msg'=>'减库存失败');
                }
            }
            //购物车更新
            $this->dbwbConn($this->dbDistributorCart)->whereIn('id', $cartids)
                ->update(['isorder' => 1, 'ordertime' => toDate()]);
            //下过单标记为老用户
            if ($uOne['is_new'] == 1) {
                $this->dbwbConn($this->dbDistributorUser)->where('id', $pas['uid'])->update(['is_new' => 0]);
            }
            //返回的参数
            $arys = [
                'orderno' => $orderno,
            ];
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success', 'data' => $arys);
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code' => -1, 'msg' => '操作失败');
        }
    }

    /**
     * 下单选项
     * @param array
     */
    public function orderOption($sku_id, $num, $uid)
    {
        $qdOne = (array) $this->dbwbConn($this->dbQdShop)->where('id', $uid)->first();
        if (empty($qdOne)) {
            return $this->toback(-2, '没有用户');
        }
        $level = $qdOne['level'];
        $arys = ['sku'=>[]];
        //商品信息
        $skuOne = (array) $this->dbwbConn($this->dbDistributorGsku)->where('id', $sku_id)->first();
        if (!empty($skuOne)) {
            $gOne = (array) $this->dbwbConn($this->dbDistributorGoods)->where('id', $skuOne['gid'])->first();
            $gname = empty($gOne) ? '' : $gOne['title'];
            $gimg = empty($gOne) ? '' : env('DOMAIN') . '/' . $gOne['bigimg'];
            $arys['sku'] = [
                'sku_id' => $sku_id,
                'sku_name' => $skuOne['title'],
                'sku_price' => $level==1 ? toNumber($skuOne['price_one']) : toNumber($skuOne['price_two']),
                'sku_num' => $num,
                'gname' => $gname,
                'gimg' => $gimg,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    /**
     * 直接下单
     * @param array $pas
     */
    public function addByGid($pas)
    {
        //用户信息
        $uOne = (array) $this->dbwbConn($this->dbDistributorUser)
            ->where('id', $pas['uid'])
            ->first();
        if (empty($uOne)) {
            return array('code' => -2, 'msg' => '用户不存在');
        }
        if (!in_array($uOne['level'], [1, 2])){
            return array('code' => -2, 'msg' => '用户级别未设置');
        }
        //收货地址
        $addressOne = (array) $this->dbwbConn($this->dbDistributorUaddress)
            ->where('del', 0)
            ->where('uid', $pas['uid'])
            ->where('id', $pas['address_id'])
            ->first();
        if (empty($addressOne)) {
            return array('code' => -2, 'msg' => '收货地址不存在');
        }
        //SKU信息
        $skuOne = (array) $this->dbwbConn($this->dbDistributorGsku)
            ->where('del', 0)
            ->where('id', $pas['sku_id'])
            ->first();
        if (empty($skuOne)) {
            return array('code' => -2, 'msg' => '规格为空');
        }
        if ($pas['num'] > $skuOne['stock']) {
            return array('code' => -2, 'msg' => '规格库存不足');
        }
        //商品信息
        $gOne = (array) $this->dbwbConn($this->dbDistributorGoods)
            ->where('del', 0)
            ->where('id', $skuOne['gid'])
            ->first();
        if (empty($gOne)) {
            return array('code' => -2, 'msg' => '商品为空');
        }
        //订单信息
        $orderno = toOrderno();
        if($uOne['level'] == 1) {
            $price = $skuOne['price_one'];
        }elseif ($uOne['level'] == 2) {
            $price = $skuOne['price_two'];
        }
        $priceTotal = $real_pay = $price  * $pas['num'];
        $orderData = [
            'from_type' => 2,
            'uid' => $pas['uid'],
            'uname' => $uOne['nickname'],
            'orderno' => $orderno,
            'tradeno' => toTradeno(),
            'address_id' => $pas['address_id'],
            'price' => $priceTotal,
            'real_pay' => $real_pay,
            'num' => $pas['num'],
            'remark' => $pas['remark'],
            'addtime' => toDate(),
        ];
        DB::beginTransaction(); //开启事务
        try {
            //订单添加
            $orderid = $this->dbwbConn($this->dbDistributorOrder)->insertGetId($orderData);
            if (!$orderid) {
                return array('code'=>-1, 'msg'=>'下单失败');
            }
            //SKU信息
            $skuAry = [
                'order_id' => $orderid,
                'gid' => $skuOne['gid'],
                'sku_id' => $pas['sku_id'],
                'gname' => $gOne['title'],
                'sku_name' => $skuOne['title'],
                'gimg' => $gOne['bigimg'],
                'price' => $price,
                'num' => $pas['num'],
                'addtime' => toDate(),
            ];
            //订单SKU
            $osid = $this->dbwbConn($this->dbDistributorOsku)->insertGetId($skuAry);
            if (!$osid) {
                return array('code'=>-1, 'msg'=>'订单SKU失败');
            }
            $stockNew = $skuOne['stock'] - $pas['num'];
            $skuData = [
                'stock' => $stockNew,
                'uptime' => toDate()
            ];
            $skuUp = $this->dbwbConn($this->dbDistributorGsku)->where('id', $pas['sku_id'])->update($skuData);
            if (!$skuUp) {
                return array('code'=>-2, 'msg'=>'减库存失败');
            }
            //下过单标记为老用户
            if ($uOne['is_new'] == 1) {
                $this->dbConn($this->dbDistributorUser)->where('id', $pas['uid'])->update(['is_new' => 0]);
            }
            //返回的参数
            $arys = [
                'orderno' => $orderno,
            ];
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success', 'data' => $arys);
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code' => -1, 'msg' => '操作失败');
        }
    }

    /**
     * 订单取消
     * @param int $id 订单ID
     */
    public function setCancel($id)
    {
        $res = (array) $this->dbwbConn($this->dbDistributorOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        if ($res['iscancel'] == 2) {
            return array('code' => -2, 'msg' => '该订单在审核中');
        }
        if ($res['iscancel'] == 3) {
            return array('code' => -2, 'msg' => '该订单已取消');
        }
        $status = $res['status']<2 ? 3 : 2; //待付款不用审核，已付款要审核
        $up = $this->dbwbConn($this->dbDistributorOrder)->where('id', $id)
            ->update(['iscancel' => $status, 'canceltime' => toDate()]);
        if (!$up) {
            return array('code' => -1, 'msg' => '操作失败');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 订单撤回
     * @param int $id 订单ID
     */
    public function setRevoke($id)
    {
        $res = (array) $this->dbwbConn($this->dbDistributorOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        if ($res['iscancel'] == 1) {
            return array('code' => -2, 'msg' => '该订单未申请');
        }
        if ($res['iscancel'] > 2) {
            return array('code' => -2, 'msg' => '该订单已审核');
        }
        $up = $this->dbwbConn($this->dbDistributorOrder)->where('id', $id)
            ->update(['iscancel' => 1]);
        if (!$up) {
            return array('code' => -1, 'msg' => '操作失败');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    /**
     * 订单
     * @param int $id 订单ID
     */
    public function setFinish($id)
    {
        $res = (array) $this->dbwbConn($this->dbDistributorOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        if ($res['status'] < 4) {
            return array('code' => -2, 'msg' => '该订单未签收');
        }
        if ($res['status'] == 5) {
            return array('code' => -2, 'msg' => '该订单已完成');
        }
        $up = $this->dbwbConn($this->dbDistributorOrder)->where('id', $id)
            ->update(['status' => 5, 'finishtime' => toDate()]);
        if (!$up) {
            return array('code' => -1, 'msg' => '操作失败');
        }
        return array('code' => 0, 'msg' => 'success');
    }

    //再来一单
    public function again($id)
    {
        //老的订单
        $oldOne = (array) $this->dbwbConn($this->dbDistributorOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($oldOne)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        //老的SKU
        $skuOlds = $this->dbwbConn($this->dbDistributorOsku)->where('order_id', $oldOne['id'])->get();
        if (!count($skuOlds)) {
            return array('code' => -2, 'msg' => '该订单信息不存在');
        }
        DB::beginTransaction(); //开启事务
        try {
            //生成订单
            $orderno = toOrderno();
            $price = $oldOne['price'];
            $orderData = [
                'uid' => $oldOne['uid'],
                'uname' => $oldOne['uname'],
                'orderno' => $orderno,
                'address_id' => $oldOne['address_id'],
                //'coupon_id' => $pas['coupon_id'],
                'price' => $price,
                'real_pay' => $price,
                'remark' => $oldOne['remark'],
                'again_id' => $oldOne['id'],
                'addtime' => toDate(),
            ];
            $orderid = $this->dbwbConn($this->dbDistributorOrder)->insertGetId($orderData);
            if (!$orderid) {
                return array('code' => -1, 'msg' => '再来一单失败');
            }
            //生成SKU
            foreach ($skuOlds as $v) {
                $v = (array) $v;
                $gArys = [
                    'order_id' => $orderid,
                    'gid' => $v['gid'],
                    'sku_id' => $v['sku_id'],
                    'gname' => $v['gname'],
                    'sku_name' => $v['sku_name'],
                    'gimg' => $v['gimg'],
                    'price' => $v['price'],
                    'num' => $v['num'],
                    'addtime' => toDate(),
                ];
                $osid = $this->dbwbConn($this->dbDistributorOsku)->insertGetId($gArys);
                if (!$osid) {
                    return array('code'=>-1, 'msg'=>'订单SKU失败');
                }
                //减库存更新
                $skuOne = (array) $this->dbwbConn($this->dbDistributorGsku)->where('id', $v['sku_id'])->first();
                if (empty($skuOne)) {
                    return array('code'=>-2, 'msg'=>'商品SKU失败');
                }
                if ($skuOne['stock'] < $v['num']) {
                    return array('code'=>-2, 'msg'=>'商品SKU不足');
                }
                $stockNew = $skuOne['stock'] - $v['num'];
                $skuData = [
                    'stock' => $stockNew,
                    'uptime' => toDate()
                ];
                if ($stockNew == 0) {
                    $skuData['del'] = 1;
                    $skuData['deltime'] = toDate();
                }
                $skuUp = $this->dbwbConn($this->dbDistributorGsku)->where('id', $v['sku_id'])->update($skuData);
                if (!$skuUp) {
                    return array('code'=>-2, 'msg'=>'减库存失败');
                }
            }
            $resData = [
                'orderid' => $orderid,
            ];
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success', 'data' => $resData);
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code' => -1, 'msg' => '操作失败');
        }
    }

    //订单详情
    public function getOne($id)
    {
        //订单
        $resOne = (array) $this->dbwbConn($this->dbDistributorOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($resOne)) {
            return array('code' => -2, 'msg' => '该订单不存在');
        }
        //SKU
        $skuOnes = $this->dbwbConn($this->dbDistributorOsku)->where('order_id', $resOne['id'])->get();
        if (!count($skuOnes)) {
            return array('code' => -2, 'msg' => '该订单信息不存在');
        }
        //状态
        $cancels = $this->orderCancels;
        $status1s = $this->orderStatus1s;
        if ($resOne['iscancel'] > 1) {
            $status_name = array_key_exists($resOne['iscancel'], $cancels) ? $cancels[$resOne['iscancel']] : '';
        } else {
            $status_name = array_key_exists($resOne['status'], $status1s) ? $status1s[$resOne['status']] : '';
        }
        //收货地址
        $addressOne = (array) $this->dbwbConn($this->dbDistributorUaddress)->where('id', $resOne['address_id'])->first();
        $street = empty($addressOne) ? '' : $addressOne['wx_door'];
        $door = empty($addressOne) ? '' : $addressOne['door'];
        $addressList = [
            'dizhi' => $street . $door,
            'phone' => empty($addressOne) ? '' : $addressOne['phone'],
            'accepter' => empty($addressOne) ? '' : $addressOne['accepter'],
        ];
        //商品信息
        $goodsList = [];
        $osOnes = $this->dbwbConn($this->dbDistributorOsku)->where('order_id', $resOne['id'])->get();
        if (count($osOnes)) {
            $gids = [];
            foreach ($osOnes as $osOne) {
                $imgOne = (array) $this->dbwbConn($this->dbDistributorGimg)
                    ->where('del', 0)
                    ->where('gid', $osOne->gid)
                    ->first();
                $gOne = (array) $this->dbwbConn($this->dbDistributorGoods)
                    ->where('del', 0)
                    ->where('id', $osOne->gid)
                    ->first();
                if (!in_array($osOne->gid, $gids) && !empty($imgOne) && !empty($gOne)) {
                    $goodsList[] = [
                        'gid' => $osOne->gid,
                        'sku_id' => $osOne->sku_id,
                        'gname' => $gOne['title'],
                        'gimg' => env('DOMAIN') . '/' . $imgOne['link'],
                        'sku_name' => $osOne->sku_name,
                        'sku_num' => $osOne->num,
                        'sku_price' => toNumber($osOne->price),
                    ];
                    $gids[] = $osOne->gid;
                }
            }
        }
        $priceTotal = $resOne['price'];
        //支付方式
        $payWays = $this->orderPayWays;
        $payWayName = array_key_exists($resOne['pay_way'], $payWays) ? $payWays[$resOne['pay_way']] : '';
        $arys = [
            'id' => $resOne['id'],
            'status' => $resOne['status'],
            'statusName' => $status_name,
            'wuliu' => $resOne['wuliu'],
            'wuliuhao' => $resOne['wuliuhao'],
            'sendtime' => $resOne['sendtime'],
            'addressList' => $addressList,
            'goodsList' => $goodsList,
            'priceTotal' => toNumber($priceTotal),
            'realPay' => toNumber($resOne['real_pay']),
            'ordertime' => $resOne['addtime'],
            'orderno' => $resOne['orderno'],
            'payWay' => $resOne['pay_way'],
            'payWayName' => $payWayName,
            'payno' => '',
            'delay' => 1,
            'iscancel' => $resOne['iscancel'],
            'remark' => $resOne['remark'],
            'tradeno' => $resOne['tradeno'],
        ];
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    //状态收货
    public function receive($id)
    {
        $order_info = (array) $this->dbwbConn($this->dbDistributorOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($order_info)) {
            return $this->toback(-2, '该订单不存在');
        }
        if ($order_info['iscancel'] > 1) {
            return $this->toback(-2, '该订单处于取消流程中');
        }
        if ($order_info['status'] != 3) {
            return $this->toback(-2, '该订单状态错误');
        }

        $order_sku = $this->dbwbConn($this->dbDistributorOsku . ' as os')
            ->leftJoin($this->dbDistributorGsku . ' as s', 's.id', '=', 'os.sku_id')
            ->select('os.id', 'os.num', 's.price')
            ->where('os.del', 0)
            ->where('os.order_id', $order_info['id'])
            ->get()
            ->map(function ($value){
                return (array)$value;
            })
            ->toArray();
        if(empty($order_sku)) {
            return $this->toback(-2, '该订单没有商品数据');
        }
        $price = 0;
        foreach ($order_sku as $item) {
            $price += $item['price'] * $item['num'];//sku总市场指导价
        }
//        $commission_rate = getConfig('commission_rate') ? getConfig('commission_rate') : 0;//佣金比例
//        $commission_rate = $commission_rate/100;
        $configOne = $this->getConfig('commission_rate');//佣金比例
        $commission_rate = $configOne['code']==0 ? $configOne['data'] : 0;
        $commission = $price * $commission_rate;
        DB::beginTransaction(); //开启事务
        try {
            $this->dbwbConn($this->dbDistributorOrder)->where('id', $id)->update([
                'status' => 4, 'finishtime' => toDate(),
            ]);
            //收益
            $income_user_id = $this->dbwbConn($this->dbDistributorUser)
                ->where('id', $order_info['uid'])
                ->value('parent_id');
            if($income_user_id){
                $incom_arr = [
                    'uid' => $income_user_id,
                    'orderno' => $order_info['orderno'],
                    'ordertime' => $order_info['addtime'],
                    'amount' => $commission,
                    'addtime' => toDate()
                ];
                $this->dbwbConn($this->dbDistributorIncome)
                    ->insertGetId($incom_arr);//收益记录
                $this->dbwbConn($this->dbDistributorUser)
                    ->where('id', $income_user_id)
                    ->increment('income', $commission);
            }
            DB::commit(); //提交事务
            return $this->toback(0, 'success');
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code' => -1, 'msg' => '操作失败');
        }
    }

    //状态自提
    public function pickup($id)
    {
        $oldOne = (array) $this->dbwbConn($this->dbDistributorOrder)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($oldOne)) {
            return $this->toback(-2, '该订单不存在');
        }
        if ($oldOne['delivery'] == 1) {
            return $this->toback(-2, '该订单属于快递');
        }
        if ($oldOne['iscancel'] > 1) {
            return $this->toback(-2, '该订单处于取消流程中');
        }
        if ($oldOne['status'] != 2) {
            return $this->toback(-2, '该订单状态错误');
        }
        $up = $this->dbwbConn($this->dbDistributorOrder)->where('id', $id)->update([
            'status' => 3, 'finishtime' => toDate(),
        ]);
        if (!$up) {
            return $this->toback(-2, '设置失败');
        }
        return $this->toback(0, 'success');
    }

    //交易流水号初始化
    public function tradeno()
    {
        $res = $this->dbConn($this->dbDistributorOrder)
            ->where('del', 0)
            ->where('tradeno', '')
            ->get();
        if (empty($res)) {
            return false;
        }
        foreach ($res as $v) {
            $v = (array) $v;
            $tradeno = date('YmdHis', strtotime($v['addtime'])) . rand(1000000000, 9999999999);
            $this->dbConn($this->dbDistributorOrder)->where('id', $v['id'])
                ->update(['tradeno' => $tradeno]);
        }
        return true;
    }

    //发货20天后自动确认收货
    public function autoAccept($uid = 0)
    {
        $day20 = date('Y-m-d H:i:s', strtotime('-20 days'));
        $db = $this->dbwbConn($this->dbQdOrder)
            ->where('del', 0)
            ->where('iscancel', 1)
            ->where('status', 3);
        if ($uid) {
            $db = $db->where('uid', $uid);
        }
        $db->where('sendtime', '<=', $day20)
            ->update(['status' => 4, 'finishtime' => toDate()]);
        return true;
//        $res = (array) $db->where('sendtime', '<=', $day20)
//            ->orderBy('id', 'desc')->first();
//        ddd($res);
    }
}